package day05;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import util.JdbcUtil;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("*.product")
public class ProductServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getServletPath();

        if ("/list.product".equals(path)) {
            list(request,response);
        }
    }

    protected void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("ProductServlet.list()");


        List<Product> products=new ArrayList<>();

        Connection con=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        try{
            con= JdbcUtil.getConnection();
            con.setAutoCommit(false);


            String sql=new StringBuffer()
                    .append("select * ")
                    .append("from t_product ")
                    .toString();

            ps=con.prepareStatement(sql);


            rs=ps.executeQuery();

            while(rs.next()){
                Product product=new Product();
                product.setId(rs.getInt("id"));
                product.setName(rs.getString("name"));
                product.setPrice(rs.getDouble("price"));
                products.add(product);
            }

            con.commit();
        }catch (Exception e){
            e.printStackTrace();
            try {
                con.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }finally{
            JdbcUtil.close(rs,ps,con);
        }

        request.setAttribute("products",products);
        request.getRequestDispatcher("/shop/list.jsp").forward(request,response);
    }
}